import { _decorator, Component, instantiate, Node, Prefab, tween, v3, view } from 'cc';
import { Logger } from 'db://assets/util';
import { Bullet } from './bullet/Bullet';
const { ccclass, property } = _decorator;

const random = (num: number) => Math.round(Math.random() * num)

enum BulletStyle {
    normal = 'normal',
    hightLight = 'hight_light',
}

@ccclass('BulletFrame')
export class BulletFrame extends Component {
    #logger = new Logger('子弹帧::BulletFrame')

    @property({
        tooltip: '子弹',
        displayName: '子弹',
        type: Prefab,
    })
    bullet: Prefab

    @property({
        tooltip: '高亮子弹',
        displayName: '高亮子弹',
        type: Prefab,
    })
    highlightBullet: Prefab

    @property({
        tooltip: '第一行',
        displayName: '第一行',
        type: Node,
    })
    line1: Node

    @property({
        tooltip: '第二行',
        displayName: '第二行',
        type: Node,
    })
    line2: Node

    @property({
        tooltip: '第三行',
        displayName: '第三行',
        type: Node,
    })
    line3: Node

    start() {
        this.#logger.debug('@start')
    }

    clear() {
        this.#logger.debug('@clear')
        this.line1.destroyAllChildren()
        this.line2.destroyAllChildren()
        this.line3.destroyAllChildren()
    }

    shootBullets(bullets: LDContent.Bullet[]) {
        for (const index in bullets) {
            const bullet = bullets[index]
            this.shootBullet(bullet, [this.line2, this.line1, this.line3][+index % 3], +index)
        }
    }

    shootBullet(bullet: LDContent.Bullet, target: Node, index: number) {
        const bulletNode = instantiate(bullet.style == BulletStyle.hightLight ? this.highlightBullet : this.bullet)
        const bulletComponent = bulletNode.getComponent(Bullet)
        bulletComponent.text = bullet.text
        target.addChild(bulletNode)
        const { width } = view.getVisibleSize()

        tween(bulletNode)
            .set({ position: v3(width + Math.round(Math.random() * width), 0) })
            .call(() => {
                this.#logger.debug('@shootBullet', bullet)
                tween(bulletNode)
                    .delay(random(index))
                    .to(6 + random(index % 3), { position: v3(-width - Math.round(Math.random() * width)) })
                    .call(() => {
                        bulletNode.destroy()
                    }).start()
            }).start()
    }
}


